package org.atguigu.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author 海晨忆
 * @Des 接受前端验证码，校验验证码
 * @Date 2025/8/1 17:13
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String captcha = request.getParameter("captcha");
        String sessionCode = (String) request.getSession().getAttribute("captcha");
        //只有登录请求才需要校验验证码
        String requestURI = request.getRequestURI();
        if ("/user/login".equals(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        if (!StringUtils.hasText(captcha)) {
            //没有验证码
            response.sendRedirect("/");
        } else if (!captcha.equalsIgnoreCase(sessionCode)) {
            //验证没通过
            response.sendRedirect("/");
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
